import axios from "axios";
import { ElMessage } from "element-plus";
// import config from "@/config";

const service = axios.create({
//   baseURL: config.baseApi,
  timeout: 30000,
});

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use((res) => {
  const headers = res.headers
  let contentDisposition = headers.get("content-disposition")
  const contentType = headers["Content-Type"]
  if(contentDisposition) {

    const index = contentDisposition.indexOf("''")
    const fileName = contentDisposition.substring(index+2)

    var blob = new Blob([res.data], {
      type: contentType
    })
    // 新窗口打开
    var url = window.URL.createObjectURL(blob)
    var a = document.createElement('a')
    a.href = url
    // 文件名
    a.download = decodeURIComponent(fileName) // 进行解码
    a.click()
  }
  
  const {code,msg} = res.data
  if (res.status != 200) {
    ElMessage.error(msg || "网络错误");
    return Promise.reject(msg || "网络错误");
  }
  return res.data;
});

function request(options) {
  options.method = options.method || "get";

  if(options.method === 'get' && options.data) {
        options.params = options.data;
  }
//   let isMock = config.isMock;
  
//   if ((typeof options.isMock) !== undefined) {
//     isMock = options.isMock;
//   }else{
//     isMock = false
//   }

//   if (config.env === 'prod') {
//     service.defaults.baseURL = config.baseApi;
//   }else{
//     service.defaults.baseURL = isMock?config.mockApi:config.baseApi;
//   }
  return service(options);
}

export default request;
